// ============================== 导入依赖 ============================== //

import CORE from '@/CORE'
import Client from '@api/flowpath/api/FlowpathTemplateApi'

import ComClass from '@api/ComQuery'
import ListClass from '@api/flowpath/model/QueryFlowpathTemplateListReq'
import OneClass from '@api/flowpath/model/QueryFlowpathTemplateDetailReq'
import AddClass from '@api/flowpath/model/InsertFlowpathTemplateReq'
import EditClass from '@api/flowpath/model/UpdateFlowpathTemplateReq'
import DelClass from '@api/flowpath/model/DeleteFlowpathTemplateReq'
import BaseClass from '@api/flowpath/model/FlowpathTemplateDto'
import FormDTO from '@api/flowpath/model/FlowpathAttributeDto'
import UserDTO from '@api/flowpath/model/FlowpathApproverDto'

const CLIENT = CORE.grpcCLIENT(Client)
const COM = [ComClass, 'comQuery']
const FORM = [FormDTO, 'attributes', 1]
const USER = [UserDTO, 'approvers', 1]
const BASE = [BaseClass, 'flowpathTemplateDto', null, (dto, obj) => CORE.grpcDTO(dto, obj, FORM, USER)]

// ============================== 导出远程接口 ============================== //

export default {
  // —————————————————————————————— 列表 —————————————————————————————— //

  async getList(param, TIP = '查询列表') {
    const DTO = CORE.grpcDTO(ListClass, param, COM, [BaseClass, 'flowpathTemplateDto'])
    const resp = await CORE.grpc(TIP, CLIENT, 'queryFlowpathTemplateList', DTO)
    return [resp.comQuery.totalCount, resp.flowpathTemplateDto || []]
  },

  // —————————————————————————————— 单项 —————————————————————————————— //

  async getOne({ id }, TIP = '查询详情') {
    const DTO = CORE.grpcDTO(OneClass, { id })
    const resp = await CORE.grpc(TIP, CLIENT, 'queryFlowpathTemplateDetail', DTO)
    return resp.flowpathTemplateDto || {}
  },
  transOne(obj) {
    obj.attributes.forEach((item) => {
      obj[`child_${item.id}`] = item.attributeCode && item.attributeName ? 'ready' : ''
    })
    return obj
  },

  // —————————————————————————————— 增 —————————————————————————————— //

  transAdd(one) {
    const attributes = one.attributes.map((item, i) => ({ ...item, sortValue: i + 1 }))
    const approvers = one.approvers.map((item, i) => ({ ...item, sortValue: i + 1 }))
    return { ...one, attributes, approvers }
  },
  async add(one, TIP = '新增') {
    const DTO = CORE.grpcDTO(AddClass, one, BASE)
    await CORE.grpc(TIP, CLIENT, 'insertFlowpathTemplate', DTO)
    return CORE.grpcOK(TIP)
  },

  // —————————————————————————————— 改 —————————————————————————————— //

  transEditToAdd: true,
  async edit(one, TIP = '修改') {
    const DTO = CORE.grpcDTO(EditClass, one, BASE)
    await CORE.grpc(TIP, CLIENT, 'updateFlowpathTemplate', DTO)
    return CORE.grpcOK(TIP)
  },

  // —————————————————————————————— 删 —————————————————————————————— //

  async del({ id }, TIP = '删除') {
    const DTO = CORE.grpcDTO(DelClass, { id })
    await CORE.grpc(TIP, CLIENT, 'deleteFlowpathTemplate', DTO)
    return CORE.grpcOK(TIP)
  },
}
